# coding:utf-8
from typing import Dict

from fastapi import Query
from tortoise.queryset import Q

from app.models.upload import Upload, UploadFolder
from app.admin.schemas.upload import UploadBase, UploadOutDB, UploadRename, FolderBase, FolderUpdate


class UploadService:
    # 列表
    async def page_list(self, query: Query, page: int = 1, limit: int = 10):
        start = (page - 1) * limit
        count = await Upload.filter(is_deleted=False).filter(query).count()
        lists = await Upload.filter(is_deleted=False).filter(query).offset(start).limit(limit).all()
        return count, lists

    async def create(self, obj_in: UploadBase):
        if isinstance(obj_in, Dict):
            obj_dict = obj_in
        else:
            obj_dict = obj_in.model_dump()
        item = await Upload.create(**obj_dict)
        return item

    async def update(self, obj_in: UploadRename):
        if isinstance(obj_in, Dict):
            obj_dict = obj_in
        else:
            obj_dict = obj_in.model_dump()

        # 删除键
        user_id = obj_dict.pop('id')
        user = await Upload.filter(id=user_id).update(**obj_dict)
        return user

    async def remove(self, item_id: int):
        user = await Upload.filter(id=item_id).first()
        if user:
            user.is_deleted = True
            await user.save()
            return True
        else:
            return False

    # 文件列表
    async def folder_list(self, query: Query):
        lists = await UploadFolder.filter(is_deleted=False).filter(query).all()
        return lists

    async def folder_create(self, obj_in: FolderBase):
        if isinstance(obj_in, Dict):
            obj_dict = obj_in
        else:
            obj_dict = obj_in.model_dump()
        item = await UploadFolder.create(**obj_dict)
        return item

    async def folder_update(self, obj_in: FolderUpdate):
        if isinstance(obj_in, Dict):
            obj_dict = obj_in
        else:
            obj_dict = obj_in.model_dump()

        # 删除键
        user_id = obj_dict.pop('id')
        user = await UploadFolder.filter(id=user_id).update(**obj_dict)
        return user

    async def folder_remove(self, item_id: int):
        user = await UploadFolder.filter(id=item_id).first()
        if user:
            user.is_deleted = True
            await user.save()
            return True
        else:
            return False
